package com.lzh.thread;

import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhehen.lu
 * @date 2025/8/13 21:05
 */
public class LzhThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private static final AtomicInteger threadNumber = new AtomicInteger(1);
    private static final String threadPoolPrefix = "lzh-pool-";
    private final ThreadGroup group;
    private final String namePrefix;

    public LzhThreadFactory(String namePrefix) {
        SecurityManager s = System.getSecurityManager();
        this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("yk-pool-").append(poolNumber.getAndIncrement());
        if (namePrefix != null && namePrefix.length() > 0) {
            stringBuilder.append("-").append(namePrefix).append("-");
        }

        this.namePrefix = stringBuilder.toString();
    }

    @Override
    public Thread newThread(Runnable r) {
        Runnable ttlRunnable = TtlRunnable.get(r);
        Thread t = new Thread(this.group, ttlRunnable, this.namePrefix + threadNumber.getAndIncrement(), 0L);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }

        if (t.getPriority() != 5) {
            t.setPriority(5);
        }

        return t;
    }

    public static Thread createThread(Runnable task, String threadName, boolean isDaemon) {
        return createThread(task, (ThreadDecorator)null, threadName, isDaemon);
    }

    public static Thread createThread(Runnable task, ThreadDecorator threadDecorator, String threadName, boolean isDaemon) {
        if (task == null) {
            throw new RuntimeException("必须传入任务");
        } else if (threadName == null) {
            throw new RuntimeException("必须传入线程名称");
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(threadName).append("-thread-").append(threadNumber.getAndIncrement());
            Runnable ttlRunnable = TtlRunnable.get(task);
            Thread thread = new Thread((Runnable)(threadDecorator == null ? ttlRunnable : threadDecorator.decorate(ttlRunnable)), stringBuilder.toString());
            thread.setDaemon(isDaemon);
            return thread;
        }
    }
}